package com.zhxh.nzpos.buyin;

import java.util.ArrayList;
import java.util.Calendar;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.format.DateFormat;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.zhxh.nzpos.BaseActivity;
import com.zhxh.nzpos.Constants;
import com.zhxh.nzpos.R;
import com.zhxh.nzpos.api.ConnectorBuyin;
import com.zhxh.nzpos.api.exception.AuthenticationException;
import com.zhxh.nzpos.api.exception.AuthorizationException;
import com.zhxh.nzpos.api.exception.CommunicationException;
import com.zhxh.nzpos.dao.BuyinDao;
import com.zhxh.nzpos.dao.GoodsDao;
import com.zhxh.nzpos.model.Buyin;
import com.zhxh.nzpos.model.Goods;
import com.zhxh.nzpos.model.Order;
import com.zhxh.nzpos.sell.ItemDeleteCallback;
import com.zhxh.nzpos.utils.PersistenceUtil;
import com.zhxh.nzpos.utils.RandomStringUtils;
import com.zhxh.nzpos.utils.ViewUtil;

/**
 * 进货管理--商品订购
 * 
 * @author wangzt
 *
 */
public class GoodsOrderActivity extends BaseActivity implements ItemDeleteCallback {
	private static final int SAVE_SUCCESS = 1;
	private static final int SAVE_FAIL = 2;
	
	private ArrayList<Buyin> orderItems;
	private OrderListAdapter listAdapter;
	private TextView payedTV;
	private EditText goodsOcr;
	
	private BuyinDao buyInDao;
	private GoodsDao goodsDao;
	private String date;
	
	private Order order = new Order();//本次订单
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			if (msg.what == SAVE_SUCCESS) {
				ViewUtil.makeToast(getApplication(), "订货成功");
				finish();
			} else if (msg.what == SAVE_FAIL) {
				ViewUtil.makeToast(getApplication(), "订货失败");
			} 
			
			ViewUtil.cancelProgressDialog();
		}
		
	};
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_buyin_order);
        buyInDao = new BuyinDao(getApplicationContext());
        goodsDao = new GoodsDao(getApplicationContext());
        order.setId(RandomStringUtils.randomNumeric(10));
        order.setOrderNumber(Integer.valueOf(RandomStringUtils.randomNumeric(4)));
        initViews();
    }
	
	private void initViews() {
		Calendar calendar = Calendar.getInstance();
		calendar.setTimeInMillis(System.currentTimeMillis());
		date = DateFormat.format("yyyy-MM-dd", calendar).toString();
		
		payedTV = (TextView) findViewById(R.id.buyin_the_pay_tv);
		
		ListView listView = (ListView) findViewById(R.id.buyin_order_listview);
		orderItems = new ArrayList<Buyin>();
		
		// TODO 扫描条码添加一项
		goodsOcr = (EditText) findViewById(R.id.buyin_ocr_et);
		Button scanBtn = (Button) findViewById(R.id.buyin_scan_btn);
		scanBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(Constants.SCAN_ACTION);
				startActivityForResult(intent, Constants.SCAN_REQUEST_CODE);
			}
		});
		
		Button addBtn = (Button) findViewById(R.id.buyin_add_btn);
		addBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Editable ocr = goodsOcr.getText();
				if (ocr!= null) {
					String ocrStr = ocr.toString();
					addBuyin(ocrStr);
					
				}
			}
		});
		
		listAdapter = new OrderListAdapter(getLayoutInflater(), orderItems, this);
		listView.setAdapter(listAdapter);
		
		Button settleBtn = (Button) findViewById(R.id.buyin_order_ok_btn);
		settleBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				ViewUtil.showProgressDialog(GoodsOrderActivity.this, "正在保存...");
				new Thread(){
					public void run() {
						if (buyInDao.saveAllAndOrder(orderItems, order)) {
							ConnectorBuyin connectorBuyin = new ConnectorBuyin();
							try {
								for (Buyin buyin : orderItems) {
										connectorBuyin.submitOrder(buyin, PersistenceUtil.getPosId(getApplicationContext()), PersistenceUtil.getOperatorCard(getApplicationContext()));
								}
							} catch (CommunicationException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (AuthorizationException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (AuthenticationException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
							handler.sendEmptyMessage(SAVE_SUCCESS);
						} else {
							handler.sendEmptyMessage(SAVE_FAIL);
						}
					}
					
				}.start();
			}
		});
		Button cancelBtn = (Button) findViewById(R.id.buyin_order_cancel_btn);
		cancelBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
			}
		});
	
	}

	private void updateOrder() {
		float count = 0;
		for (Buyin buyin : orderItems) {
			count += buyin.getTotal();
		}
		order.setTotalCount(count);
		order.setHasPayed(count);
		payedTV.setText(getResources().getString(R.string.buyin_the_pay)+count);
	}
	
	@Override
	public void onDelete(int pos) {
		orderItems.remove(pos);
		listAdapter.notifyDataSetChanged();
		updateOrder();
	}

	@Override
	public void onUpdate() {
		updateOrder();
		
	}

	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		if (requestCode == Constants.SCAN_REQUEST_CODE) {
			if (resultCode == RESULT_OK) {
				String ocrStr = intent.getStringExtra(Constants.SCAN_RESULT_EXTRA);
				if (!TextUtils.isEmpty(ocrStr)) {
					goodsOcr.setText(ocrStr);
					addBuyin(ocrStr);
				} else {
					Toast.makeText(getApplicationContext(), "请重新扫描！",
							Toast.LENGTH_LONG).show();
				}

			} else if (resultCode == RESULT_CANCELED) {
				Toast.makeText(getApplicationContext(), "请重新扫描！",
						Toast.LENGTH_LONG).show();
			}
		}
	}
    
	private void addBuyin(String ocrStr) {
		Goods goods = goodsDao.find(ocrStr);
		if (goods != null) {
			
			Buyin buyin = new Buyin();
			buyin.setGoodId(ocrStr);
			buyin.setName(goods.getName());
			buyin.setPrice(goods.getPrice1());
			buyin.setCount(1);//默认添加一个
			buyin.setBuyinDate(date);
			// TODO 获取operator id 和 supplier id
			buyin.setOpratorId(PersistenceUtil.getOperatorCard(getApplicationContext()));
			buyin.setOrderId(order.getId());
			buyin.setPayed(true);
			buyin.setReceived(false);
			buyin.setSupplierId("4444");
			buyin.setCategoryId(goods.getCategoryId());
			buyin.setUnits(goods.getUnits1()); 
			buyin.setSpecification(goods.getSpecification());
			orderItems.add(buyin);
			if (listAdapter != null) {
				listAdapter.notifyDataSetChanged();
			}
			updateOrder();
		} else {
			ViewUtil.makeToast(GoodsOrderActivity.this, "商品未录入，请先录入商品信息");
		}
	}
}
